﻿using Application.Common.Interfaces;
using Application.Features.Roles.Commands.Delete;
using FluentValidation;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Roles.Delete;

/// <summary>
/// 校验修改角色信息
/// </summary>
public class DeleteRoleCommandValidator : AbstractValidator<DeleteRoleCommand>
{
    private readonly IApplicationDbContext _context;
    public DeleteRoleCommandValidator(IApplicationDbContext context)
    {
        _context = context;

        RuleFor(x => x.RoleIds).MustAsync(RoleExistsAsync).WithMessage("非法数据！");

        RuleFor(x => x.RoleIds).MustAsync(AllowedDeleteUserAsync).WithMessage("禁止删除！");
    }

    private async Task<bool> RoleExistsAsync(List<long> roleIds, CancellationToken cancellationToken)
    {
        var existingRoles = await _context.Roles.Where(x => roleIds.Contains(x.Id)).ToListAsync();

        if (existingRoles == null || roleIds.Count != existingRoles.Count)
        {
            return false;
        }

        // 检查是否所有传入的角色ID都在数据库中存在且数量一致
        bool allIdsMatched = existingRoles.Select(r => r.Id).All(id => roleIds.Contains(id));

        return allIdsMatched;
    }

    private async Task<bool> AllowedDeleteUserAsync(List<long> roleIds, CancellationToken cancellationToken)
    {
        var existingRoles = await _context.Roles.Where(x => roleIds.Contains(x.Id)).ToListAsync();

        if (existingRoles == null)
        {
            return false;
        }
        foreach (var item in existingRoles)
        {
            if (string.Equals(item.RoleCode,"admin",StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }
        }

        return true;
    }
}